from django.db import models


# Create your models here.


class Follow(models.Model):
    user = models.ForeignKey(verbose_name='用户/粉丝', to='account.UserInfo',
                             on_delete=models.CASCADE, related_name='my_follow')  # ForeignKey 这里应该用多对多的关系。
    follow = models.ForeignKey(verbose_name='我关注的人', to='account.UserInfo',
                               on_delete=models.CASCADE, related_name='who_follow_me')  # ForeignKey 这里应该用多对多的关系。
    is_friend = models.BooleanField(verbose_name='朋友关系', default=False)
    create_datetime = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    # def __str__(self):
    #     return f'{self.my_follow} follow {self.who_follow_me}'

    # 关注
    @staticmethod
    def follow_someone(from_user, to_user):
        follow = Follow.objects.filter(user=from_user, follow=to_user).first()
        if not follow:
            fans = Follow.objects.filter(user=to_user, follow=from_user).first()
            if not fans:    # 对方是否关注了我
                # 没有关注，直接保存
                Follow(user=from_user, follow=to_user).save()
            else:
                # 如果对方也关注了我，保存双方为好友关系
                Follow(user=from_user, follow=to_user, is_friend=True).save()
                fans.is_friend = True
                fans.save()

    # 取关
    @staticmethod
    def unfollow_someone(from_user, to_user):
        f = Follow.objects.filter(user=from_user, follow=to_user).first()
        if f:
            # 查找对方是否有关注了我
            fans = Follow.objects.filter(user=to_user, follow=from_user).first()
            if fans:
                fans.is_friend = False
                fans.save()
            f.delete()

    # 得到from_user关注的人，返回列表
    @staticmethod
    def user_followed(from_user):
        followeders = Follow.objects.filter(user=from_user).all()
        my_follows = []
        for followeder in followeders:
            my_follows.append(followeder.follow)
        return my_follows

    # 得到from_user的好友列表
    @staticmethod
    def my_friends(from_user):
        my_friends = []
        friends = Follow.objects.filter(user=from_user, is_friend=True).all()
        for friend in friends:
            my_friends.append(friend.follow)
        return my_friends
